package com.open.video.util;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadFileStreamRequest;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.req.UploadVideoRequest;
import com.aliyun.vod.upload.resp.UploadFileStreamResponse;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyun.vod.upload.resp.UploadVideoResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoRequest;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.google.gson.Gson;

import java.io.InputStream;

public class UploadVideoDemo {
    //账号AK信息请填写(必选)
    private static final String accessKeyId = "LTAI4G8DAavn384of3YfTg2p";
    //账号AK信息请填写(必选)
    private static final String accessKeySecret = "zhmdVr5BzWLJ49oKCQcLPTutIvAPZB";

    //批量上传逻辑：
    //先上传文件，返回videoid，先把videoid存到数据库里，等待成功回调，在回调时数据库查找对应videoid，存放视频地址
    //单视频上传逻辑：
    //上传文件，等待上传完成，再拿播放地址存到数据库

//    public static void main(String[] args) {
//        JSONObject json = UploadVideo("视屏.mp4","D:\\文本\\m2.mp4");
//        try {
//            //注意！如果不sleep的话视频刚上传成功的状态是跟不上运行的
//            //会报错视频状态不是上传成功状态
//            //sleep时间按照自己视频大小去改
//            Thread.sleep(10000);
//        } catch (InterruptedException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//        String url = GetPlayInfo((String)json.get("vid"));
//        System.out.println(url);
//    }

    public static JSONObject UploadVideo(String title, String fileName) {
        UploadVideoRequest request = new UploadVideoRequest(accessKeyId, accessKeySecret, title, fileName);
        /* 可指定分片上传时每个分片的大小，默认为2M字节 */
        request.setPartSize(2 * 1024 * 1024L);
        /* 可指定分片上传时的并发线程数，默认为1，(注：该配置会占用服务器CPU资源，需根据服务器情况指定）*/
        request.setTaskNum(1);
        /* 是否开启断点续传, 默认断点续传功能关闭。当网络不稳定或者程序崩溃时，再次发起相同上传请求，可以继续未完成的上传任务，适用于超时3000秒仍不能上传完成的大文件。
        注意: 断点续传开启后，会在上传过程中将上传位置写入本地磁盘文件，影响文件上传速度，请您根据实际情况选择是否开启*/
        //request.setEnableCheckpoint(false);
        /* OSS慢请求日志打印超时时间，是指每个分片上传时间超过该阈值时会打印debug日志，如果想屏蔽此日志，请调整该阈值。单位: 毫秒，默认为300000毫秒*/
        //request.setSlowRequestsThreshold(300000L);
        /* 可指定每个分片慢请求时打印日志的时间阈值，默认为300s*/
        //request.setSlowRequestsThreshold(300000L);
        /* 是否显示水印(可选)，指定模板组ID时，根据模板组配置确定是否显示水印*/
        request.setIsShowWaterMark(false);
        /* 设置上传完成后的回调URL(可选)，建议您通过点播控制台配置事件通知，参见文档 https://help.aliyun.com/document_detail/55627.html */
        //request.setCallback("http://callback.sample.com");
        /* 自定义消息回调设置(可选)，参数说明参考文档 https://help.aliyun.com/document_detail/86952.html#UserData */
        // request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackURL\":\"http://test.test.com\"}}");
        /* 视频分类ID(可选) */
        //request.setCateId(0);
        /* 视频标签,多个用逗号分隔(可选) */
        //request.setTags("标签1,标签2");
        /* 视频描述(可选) */
        //request.setDescription("视频描述");
        /* 封面图片(可选) */
        //request.setCoverURL("http://cover.sample.com/sample.jpg");
        /* 模板组ID(可选) */
        //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56a33d");
        /* 工作流ID(可选) */
        //request.setWorkflowId("d4430d07361f0*be1339577859b0177b");
        /* 存储区域(可选) */
        //request.setStorageLocation("in-201703232118266-5sejdln9o.oss-cn-shanghai.aliyuncs.com");
        /* 开启默认上传进度回调 */
        //request.setPrintProgress(false);
        /* 设置自定义上传进度回调 (必须继承 VoDProgressListener) */
        //request.setProgressListener(new PutObjectProgressListener());
        /* 设置您实现的生成STS信息的接口实现类*/
        // request.setVoDRefreshSTSTokenListener(new RefreshSTSTokenImpl());
        /* 设置应用ID*/
        //request.setAppId("app-1000000");
        /* 点播服务接入点 */
        //request.setApiRegionId("cn-shanghai");
        /* ECS部署区域*/
        // request.setEcsRegionId("cn-shanghai");
        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadVideoResponse response = uploader.uploadVideo(request);
        System.out.print("RequestId=" + response.getRequestId() + "\n");  //请求视频点播服务的请求ID
        JSONObject json = new JSONObject();
        if (response.isSuccess()) {
            System.out.print("VideoId=" + response.getVideoId() + "\n");
            //这里我用json接收vid以后批量上传会用到
            json.put("status",1);
            json.put("vid",response.getVideoId());
            return json;
        } else {
            /* 上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因 */
            if(response.getVideoId()==null||response.getVideoId()=="") {
                json.put("status",2);
                //这里是上传失败的逻辑，可以根据错误代码自己百度
            }
            System.out.print("ErrorCode=" + response.getCode() + "\n");
            System.out.print("ErrorMessage=" + response.getMessage() + "\n");
            return json;
        }
    }



    /**
     * 文件流上传接口
     *
     * @param title
     * @param fileName
     */
    public static  JSONObject testUploadFileStream(String title, String fileName , InputStream inputStream) {
        UploadStreamRequest request = new UploadStreamRequest(accessKeyId, accessKeySecret, title, fileName,inputStream);
        /* 是否使用默认水印(可选)，指定模板组ID时，根据模板组配置确定是否使用默认水印*/
        //request.setShowWaterMark(true);
        /* 自定义消息回调设置，参数说明参考文档 https://help.aliyun.com/document_detail/86952.html#UserData */
        //request.setUserData(""{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackURL\":\"http://test.test.com\"}}"");
        /* 视频分类ID(可选) */
        //request.setCateId(0);
        /* 视频标签,多个用逗号分隔(可选) */
        //request.setTags("标签1,标签2");
        /* 视频描述(可选) */
        //request.setDescription("视频描述");
        /* 封面图片(可选) */
        //request.setCoverURL("http://cover.sample.com/sample.jpg");
        /* 模板组ID(可选) */
        //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56a33d");
        /* 工作流ID(可选) */
        //request.setWorkflowId("d4430d07361f0*be1339577859b0177b");
        /* 存储区域(可选) */
        //request.setStorageLocation("in-201703232118266-5sejdln9o.oss-cn-shanghai.aliyuncs.com");
        /* 开启默认上传进度回调 */
        //request.setPrintProgress(true);
        /* 设置自定义上传进度回调 (必须继承 VoDProgressListener) */
        //request.setProgressListener(new PutObjectProgressListener());
        /* 设置应用ID*/
        //request.setAppId("app-1000000");
        /* 点播服务接入点 */
        //request.setApiRegionId("cn-shanghai");
        /* ECS部署区域*/
        // request.setEcsRegionId("cn-shanghai");
        JSONObject json = new JSONObject();

        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadStreamResponse response = uploader.uploadStream(request);

        System.out.print("RequestId=" + response.getRequestId() + "\n"); //请求视频点播服务的请求ID
        if (response.isSuccess()) {
            System.out.print("VideoId=" + response.getVideoId() + "\n");
            //这里我用json接收vid以后批量上传会用到
            json.put("status",1);
            json.put("vid",response.getVideoId());
            return json;
        } else {
            if(response.getVideoId()==null||response.getVideoId()=="") {
                json.put("status",2);
                //这里是上传失败的逻辑，可以根据错误代码自己百度

            }
            /* 如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因 */
            System.out.print("VideoId=" + response.getVideoId() + "\n");
            System.out.print("ErrorCode=" + response.getCode() + "\n");
            System.out.print("ErrorMessage=" + response.getMessage() + "\n");
            return json;
        }
    }





    /**
     * 获取上传视频地址接口
     *
     * @param vid
     */
    public static String GetPlayInfo(String vid) {
        // 创建SubmitMediaInfoJob实例并初始化
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-Shanghai",                // // 点播服务所在的地域ID，中国大陆地域请填cn-shanghai
                accessKeyId,        // 您的AccessKey ID
                accessKeySecret );    // 您的AccessKey Secret
        IAcsClient client = new DefaultAcsClient(profile);
        GetPlayInfoRequest request1 = new GetPlayInfoRequest();
        // 视频ID。
        request1.setVideoId(vid);
        String url = null;
        String newurl=null;
        try {
            GetPlayInfoResponse response1 = client.getAcsResponse(request1);
            System.out.println(new Gson().toJson(response1));
            for (GetPlayInfoResponse.PlayInfo playInfo : response1.getPlayInfoList()) {
                // 播放地址
                System.out.println("PlayInfo.PlayURL = " + playInfo.getPlayURL());
                String str = playInfo.getPlayURL();
                //这里会返回m3u8和mp4格式，m3u8需要转码，看自己情况
                //如果播放地址后缀为mp4返回
                if(str != null || str != "") {
//                    if(str.substring(str.length()-3,str.length()).equals("mp4")) {
                        url = playInfo.getPlayURL();
                        int index=url.indexOf("?");
                         newurl=url.substring(0,index);
//                    }
                }
            }
            return newurl;
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
        return null;
    }

    /**
     * 删除aliyun视屏接口调用方法
     * @param client
     * @param vid
     * @return
     * @throws ClientException
     */

    public static DeleteVideoResponse deleteVideo(DefaultAcsClient client,String vid) throws ClientException {
        DeleteVideoRequest request = new DeleteVideoRequest();
        //支持传入多个视频ID，多个用逗号分隔
        request.setVideoIds(vid);
        return client.getAcsResponse(request);

    }

    /**
     * 获得默认的client
     * @param accessKeyId
     * @param accessKeySecret
     * @return
     * @throws ClientException
     */
    public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
        String regionId = "cn-shanghai";  // 点播服务接入区域
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        return client;
    }
    /**
     * 删除接口
     * @param vid
     * @return
     */
    public static String deletesVideo(String vid){
        DefaultAcsClient client = null;
        try {
            client = initVodClient(accessKeyId, accessKeySecret);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        DeleteVideoResponse response = new DeleteVideoResponse();
        try {
            response = deleteVideo(client,vid);
        } catch (Exception e) {
            System.out.print("ErrorMessage = " + e.getLocalizedMessage());
            return "vid错误或者失效删除失败";
        }
        System.out.print("RequestId = " + response.getRequestId() + "\n");
        if(response!=null){
            return "删除成功";
        }
        else {
            return "删除失败";
        }
    }
}
